// stock/stock_custom_update/stock_custom_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableid: '',  //模块id
    rowid: '',  //行id
    isDisplay: true,
    status: 'edit',  //页面状态：edit,add
    approveFlag: false,
    aprRowid: '',
  },

  /**
   * 保存数据
   * @param e
   * 1、获取固定接口所需传的参数
   * 1.1、提交固定接口
   * 1.2、获取提交成功返回的row_id
   * 1.3、把row_id传入自定义接口提交自定义数据
   *
   * 2、保存数据成功
   *
   * 3、判断新增保存
   * 3.1、获取模块参数
   * 3.2、判断该模块是否启用审批
   * 3.3、启用了审批，插槽中显示审批组件，提交审批
   * 3.4、取消提交，新增数据则保留当前页面，清空数据
   * 3.5、取消提交，返回上一页
   * 3.6、没有启用审批，新增数据则保留当前页面，清空数据
   * 3.7、没有启用审批，返回上一页
   *
   * 4、判断编辑保存，保留当前页面，页面改为只读状态
   */
  bindSave(e){
    let {data,defData,defDetail} = e.detail,
      formObj = data.entity,
      details = data.details;
    wx.$each(formObj,(key,val)=>{
      if (key.indexOf(';') >= 0){
        delete data.entity[key]
      }
    });

    let {tableid} = this.data,
      url = '',
      pm1 = null;
    wx.showLoading({mask: true});
    switch (tableid) {
      //商品期初
      case 'goods_opening_balance':
        pm1 = this.openingBalance(data,defData);
        break;
      case 'assembly_order':
        pm1 = this.assemblyOrder(data,defData,defDetail);
        break;
      case 'disassembly_order':
        pm1 = this.disassemblyOrder(data,defData,defDetail);
        break;
      case 'transfer_order':
        pm1 = this.transferOrder(data,defData,defDetail);
        break;
    }
    let pm2 = pm1 && pm1.then(post=>{
      return this.submitData2(post);
    });

    pm2.then(async ()=>{
      wx.$toast("保存成功！");
      this.refreshList();

      let pageStatus = this.data.status,
        isShow = e.detail.isShow;
      if (pageStatus === 'add'){  //当前新增界面
        //获取审批信息
        await this.getEntityParam(this.data.tableid);

        if (this.data.entityPatam.is_verify) {  //当前编辑界面、已启用审批
          this.setData({
            aprRowid: data[0].row_id,
            approveFlag: true,
            newApprove: true,
            newShow: isShow
          });
        }else if (isShow){ //没有启用审批、新增数据
          this.setData({
            rowid: 0,
            status: 'add'
          })
        }else { //没有启用审批、返回上一页
          wx.navigateBack({ //跳转到前一个页面
            delta:1,//前一个页面
          })
        }
        return
      }
      if (isShow){
        this.setData({
          rowid: 0,
          status: 'add'
        });
        return
      }
      this.setData({
        isDisplay: true
      });
    })


  },
  //验证
  validForm(validObj,formObj,defData){
    return new Promise(resolve => {
      let obj = {},
        flag = false;
      wx.$each(validObj,(key,val)=>{
        obj[key] = formObj[key] || defData[key];
        if (!obj[key] && val){
          wx.$toast(val);
          flag = true;
          return false;
        }
      });
      if (flag)return;
      if (formObj.row_id){ obj.row_id = formObj.row_id}
      resolve(obj);
    })
  },
  submitData1(url,post,url2){
    return new Promise(resolve => {
      wx.$post(1,url,post).then(async res=>{
        if (res.errcode != 0)return;
        let row = res.data.row[0],
          row_id = row && row.row_id,
          newData = null;
        await this.getData(row_id,url2).then(row=>{
          newData = row;
        });
        resolve(newData);
      })
    });
  },
  submitData2(formObj){
    let post = { "table": {
        "table_id": this.data.tableid,
        "entitys": [formObj]
        /*"entitys": [{
          "entity": formObj,
          "details": []
        }]*/
      }};
    return new Promise(resolve => {
      wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(res=>{
        if (res.errcode != 0)return;
        resolve(res.data.row[0] && res.data.row[0].entity);
      })
    })
  },

  //组装单保存处理数据
  assemblyOrder(data,defData,defDetail){
    return new Promise(resolve => {
      let mainData = data.entity,
        detailData = data.details[0] && data.details[0].entitys,
        defDetailData = defDetail[0] && defDetail[0].entitys;

      let fieldArr = ['quote_goods','Order_date','entry_Warehouse','goods_unit_quantity','goods_model','quote_unit','assembly_price','goods_unit_price','price'],
        errmsg = {
          'quote_goods':'请选择一个组合件！',
          'Order_date': '请选择单据日期！',
          'entry_Warehouse': '组合件的仓库不能为空！',
          'goods_unit_quantity': '组合件的数量不能为0！'
        },
        post = {row_id: mainData.row_id || 0},
        istrue = false;

      wx.$each(fieldArr, (i,item)=> {
        let val = mainData[item.toLowerCase()] || defData[item.toLowerCase()];;
        item === 'goods_unit_quantity' && (val = parseFloat(val));
        if (!val && errmsg[item]){
          istrue = true;
          wx.$toast(errmsg[item]);
          return false;
        }
        post[item] = val;

      });
      if (istrue)return;

      let details = [],
        assembly = post.quote_goods,
        istrue1 = false;

      detailData && wx.$each(detailData,(i,item)=>{
        let data = item.entity,
          defData = defDetailData[i].entity,
          arr = ['goods_unit_quantity','quote_goods','goods_model','goods_type','goods_brand','goods_place','quote_unit','goods_unit_price','price','abstract'],
          errmsg = {'goods_unit_quantity': '子件数量不能为0！'},
          obj = {"row_id": data.row_id || defData.row_id || 0, "parent_row_id": data.parent_row_id || defData.parent_row_id || 0,},
          istrue2 = false;

        if ((data.quote_goods || defData.quote_goods) == assembly){
          istrue1 = true;
          wx.$toast('组合件不能和子件为同一商品！');
          return false;
        }

        let warehouse = data.deliver_warehouse || defData.deliver_warehouse;
        if(!warehouse){
          istrue1 = true;
          wx.$toast('子件仓库不能为空！');
          return false;
        }
        obj.warehouse = warehouse;

        wx.$each(arr,(ind,ite)=> {
          let val = data[ite.toLowerCase()] || defData[ite.toLowerCase()];
          ite === 'goods_unit_quantity' && (val = parseFloat(val || 0));
          //必填项为空时提示并跳出循环
          if (errmsg[ite] && !val){
            wx.$toast(errmsg[ite]);
            istrue2 = true;
            return false
          }

          obj[ite] = val || '';
        });
        //退出循环
        if (istrue2) {
          istrue1 = true;
          return false;
        }
        details.push(obj);
      });
      if (istrue1){
        return
      }
      if (details.length === 0){
        wx.$toast('请至少选择一个子件！');
        return
      }
      post.details = details;


      let url = 'Stock/update_assembly_order',
        url2 = 'Stock/get_assembly_order'
      this.submitData1(url,post,url2).then(newData=>{

        let newMain = newData && newData.entity[0],
          newDetails = newData && newData.detail1 && newData.detail1.entity || [];
        mainData.row_id = newMain.row_id;
        mainData.Order_No = newMain.Order_No;
        mainData.goods_unit_price = newMain.goods_unit_price;
        mainData.price = newMain.price;

        wx.$each(detailData,(i,item)=>{
          if (!newDetails[i])return;
          let data = item.entity;
          data.parent_row_id = newDetails[i].parent_row_id;
          data.row_id = newDetails[i].row_id;
          data.goods_unit_price = newDetails[i].goods_unit_price;
          data.price = newDetails[i].price;
        });

        resolve(data);
      });
    })
  },
  //拆卸单保存处理数据
  disassemblyOrder(data,defData,defDetail){
    return new Promise(resolve => {
      let mainData = data.entity,
        detailData = data.details[0] && data.details[0].entitys,
        defDetailData = defDetail[0] && defDetail[0].entitys;

      let fieldArr = ['quote_goods', 'Order_date', 'deliver_Warehouse', 'goods_unit_quantity', 'goods_model', 'quote_unit', 'disassembly_price', 'goods_unit_price', 'price', 'is_auto_share', ],
        errmsg = {
          'quote_goods':'请选择一个组合件！',
          'Order_date': '请选择单据日期！',
          'deliver_Warehouse': '组合件的仓库不能为空！',
          'goods_unit_quantity': '组合件的数量不能为0！'
        },
        post = {"row_id": mainData.row_id || 0},
        istrue = false;
      wx.$each(fieldArr, (i,item)=> {
        let val = mainData[item.toLowerCase()] || defData[item.toLowerCase()];
        ['goods_unit_quantity','disassembly_price','price','goods_unit_price'].includes(item) && (val = parseFloat(val || 0));
        if (!val && errmsg[item]){
          istrue = true;
          wx.$toast(errmsg[item]);
          return false;
        }
        post[item] = val;
      });
      if (istrue)return;

      let details = [],
        disassembly = post.quote_goods,
        istrue1 = false,
        totalPrice = 0;
      detailData && wx.$each(detailData,(i,item)=>{
        let data = item.entity,
          defData = defDetailData[i].entity,
          arr = ['goods_unit_quantity','price','quote_goods', 'goods_model', 'goods_type', 'goods_brand', 'goods_place', 'quote_unit', 'goods_unit_price',  'abstract'],
          errmsg = {'goods_unit_quantity': '子件数量不能为0！', 'price': ''},
          obj = {"row_id": data.row_id ||defData.row_id || 0, "parent_row_id": data.parent_row_id || defData.parent_row_id || 0,},
          istrue2 = false;

        if ((data.quote_goods || defData.quote_goods) == disassembly){
          istrue1 = true;
          wx.$toast('组合件不能和子件为同一商品！');
          return false;
        }

        let warehouse = data.entry_Warehouse || defData.entry_Warehouse;
        if(!warehouse){
          istrue1 = true;
          wx.$toast('子件仓库不能为空！');
          return false;
        }
        obj.warehouse = warehouse;

        wx.$each(arr,(ind,ite)=> {
          let val = data[ite.toLowerCase()] || defData[ite.toLowerCase()];
          ['goods_unit_quantity','price'].includes(item) && (val = parseFloat(val || 0));
          //必填项为空时提示并跳出循环
          if (errmsg[ite] && !val){
            wx.$toast(errmsg[ite]);
            istrue2 = true;
            return false
          }
          if (item === 'price' && !post.is_auto_share && !val){
            wx.$toast('子件入库成本不能为0！');
            istrue2 = true;
            return false
          }

          obj[ite] = val || '';
        });
        //退出循环
        if (istrue2) {
          istrue1 = true;
          return false;
        }
        totalPrice += parseFloat(data.price || defData.price);
        details.push(obj);
      });
      if (istrue1){
        return
      }
      //判断子件金额合计是否等于组合件拆卸费+出库成本
      if (!post.is_auto_share) {
        if ((post.price + post.disassembly_price) != totalPrice){
          wx.$toast('子件入库成本合计不等于组合件的拆卸费用+出库成本');
          return
        }
      }
      if (details.length === 0){
        wx.$toast('请至少选择一个子件！');
        return
      }
      post.details = details;
      //自动分摊
      if (post.is_auto_share){
        this.autoShare(post,detailData)
      }

      let url = 'Stock/update_disassembly_order',
        url2 = 'Stock/get_disassembly_order';
      this.submitData1(url,post,url2).then(newData=>{
        let newMain = newData && newData.entity[0],
          newDetails = newData && newData.detail1 && newData.detail1.entity || [];
        mainData.row_id = newMain.row_id;
        mainData.Order_No = newMain.Order_No;

        wx.$each(detailData,(i,item)=>{
          if (!newDetails[i])return;
          let data = item.entity;

          let {parent_row_id,row_id,goods_unit_price,price} = newDetails[i]

          item.entity = {...data,parent_row_id,row_id,goods_unit_price,price};
          details[i] = {...details[i],parent_row_id,row_id,goods_unit_price,price};

        });

        resolve(data);
      });


    })
  },
  //调拨单保存处理数据
  transferOrder(data,defData,defDetail){
    return new Promise(resolve => {
      let mainData = data.entity,
        detailData = data.details[0] && data.details[0].entitys,
        defDetailData = defDetail[0] && defDetail[0].entitys;

      let fieldArr = ['Order_date','deliver_Warehouse','entry_Warehouse'],
        errmsg = {
          'Order_date': '请选择单据日期！',
          'deliver_Warehouse': '调出仓库不能为空！',
          'entry_Warehouse': '调入仓库不能为空！',
        },
        post = {row_id: mainData.row_id || 0},
        istrue = false;
      wx.$each(fieldArr, (i,item)=> {

        let val = mainData[item.toLowerCase()] || defData[item.toLowerCase()];
        if (!val && errmsg[item]){
          istrue = true;
          wx.$toast(errmsg[item]);
          return false;
        }
        post[item] = val;

      });
      if (istrue)return;
      if (post.deliver_Warehouse === post.entry_Warehouse) {
        wx.$toast('调出仓库不能和调入仓库一致！');
        return
      }
      let details = [],
        assembly = post.quote_goods,
        istrue1 = false;
      detailData && wx.$each(detailData,(i,item)=>{
        let data = item.entity,
          defData = defDetailData[i].entity,
          arr = ['goods_unit_quantity','quote_goods','goods_model','goods_type','goods_brand','goods_place','quote_unit','abstract'],
          errmsg = {'goods_unit_quantity': '商品数量不能为0！'},
          obj = {"row_id": data.row_id || defData.row_id || 0, "parent_row_id": data.parent_row_id || defData.parent_row_id || 0,},
          istrue2 = false;

        wx.$each(arr,(ind,ite)=> {
          let val = data[ite.toLowerCase()] || defData[ite.toLowerCase()];
          ite === 'goods_unit_quantity' && (val = parseFloat(val || 0));
          //必填项为空时提示并跳出循环
          if (errmsg[ite] && !val){
            wx.$toast(errmsg[ite]);
            istrue2 = true;
            return false
          }

          obj[ite] = val || '';
        });
        //退出循环
        if (istrue2) {
          istrue1 = true;
          return false;
        }
        details.push(obj);
      });
      if (istrue1){
        return
      }
      if (details.length === 0){
        wx.$toast('请至少选择一个商品！');
        return
      }
      post.details = details;

      let url = 'Stock/update_transfer_order',
      url2 = 'Stock/get_transfer_order';
      this.submitData1(url,post,url2).then(newData=>{

        let newMain = newData && newData.entity[0],
          newDetails = newData && newData.detail1 && newData.detail1.entity || [];
        mainData.row_id = newMain.row_id;

        wx.$each(detailData,(i,item)=>{
          if (!newDetails[i])return;
          let data = item.entity;
          data.parent_row_id = newDetails[i].parent_row_id;
          data.row_id = newDetails[i].row_id;
        });
        resolve(data);
      });

    })
  },
  //商品期初保存处理数据
  openingBalance(data,defData){
    let validObj = {
      'quote_goods': '请先选择商品！',
      'quote_Warehouse': '请先选择仓库！',
      'goods_unit_quantity': '商品数量不能为空！',
      'price': '商品金额不能为空！',
      'goods_unit_price': '',
      'quote_unit':''
    },
      formObj = data.entity;
    return new Promise(resolve => {
      let obj = {},
        flag = false;
      wx.$each(validObj,(key,val)=>{
        obj[key] = formObj[key] || defData[key];
        if (!obj[key] && val){
          wx.$toast(val);
          flag = true;
          return false;
        }
      });
      if (flag)return;
      if (formObj.row_id){ obj.row_id = formObj.row_id}

      let url = 'Stock/update_goods_opening_balance';
      wx.$post(1,url,obj).then(res=>{
        if (res.errcode != 0)return;
        let row = res.data.row[0],
          row_id = row && row.row_id;
        formObj.row_id = row_id;

        resolve(data);
      })
    })
  },

  //拆卸单自动分摊
  autoShare: function (post,cusDetail) {
    let parPrice = parseFloat(post.price) + parseFloat(post.disassembly_price),
      detail = post.details,
      childPrice = 0;
    detail.map(item=>{
      childPrice += parseFloat(item.price);
    });
    if (!childPrice){
      wx.$each(detail, (i,item)=> {
        let cusItem = cusDetail[i].entity,
          price = parseFloat((parPrice / (detail.length-i)).toFixed(2)),
          goods_unit_price = 0;
        childPrice -= parseFloat(item.price);
        item.price = price;
        cusItem.price = price;
        goods_unit_price = parseFloat((price/parseFloat(item.goods_unit_quantity)).toFixed(2));

        item.goods_unit_price = goods_unit_price ;
        cusItem.goods_unit_price = goods_unit_price;

        parPrice -= price;
      });
      return;
    }
    wx.$each(detail, (i,item)=> {
      let cusItem = cusDetail[i].entity,    //明细数据
        price = parseFloat((parseFloat(item.price) / childPrice * parPrice).toFixed(2)),    //按比例计算金额
        goods_unit_price = 0;
      childPrice -= parseFloat(item.price);
      item.price = price;
      cusItem.price = price;
      goods_unit_price = parseFloat((parseFloat(item.price)/parseFloat(item.goods_unit_quantity)).toFixed(2));
      item.goods_unit_price = goods_unit_price;
      cusItem.goods_unit_price = goods_unit_price;

      parPrice -= price;
    });
  },

  //获取数据
  getData(rid,url ){
    let post = {"row_id": rid};
    return new Promise(resolve => {
      wx.$post(1,url,post).then(res=>{
        resolve(res.data.row[0])
      })
    })
  },

  //新增提交审批后操作
  bindNewApprove(){
    let {newApprove,newShow} = this.data;
    if (newApprove) { //新增审批
      if (newShow) {  //新增数据
        this.setData({
          rowid: 0,
          status: 'add',
          aprRowid: 0,
          approveFlag: false,
          newApprove: false,
          newShow: false
        });
        return
      }
      //跳转到前一个页面
      wx.navigateBack({
        delta:1,//前一个页面
      })
    }
  },
  saveData(detail){
    let {tableid} = this.data,
      url = '',
      validObj = {};
    switch (tableid) {
      case 'goods_opening_balance':
        url = 'Stock/update_goods_opening_balance';
        validObj = {
          'quote_goods': '请先选择商品！',
          'quote_Warehouse': '请先选择仓库！',
          'goods_unit_quantity': '商品数量不能为空！',
          'price': '商品金额不能为空！',
          'goods_unit_price': '',
          'quote_unit':''
        };
        break;
    }
    return new Promise(resolve => {
      Promise.all([this.validForm(),this.submitData()]).then(res=>{

        wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(res=>{
          if (res.errcode != 0)return;
          resolve(res.data.row[0] && res.data.row[0].entity);
        })
      })
    })
  },

  //获取模块参数
  getEntityParam(tableid){
    return new Promise(resolve => {
      wx.$post(3,'Entity_param/query_entity_param',{table_id: tableid}).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row[0];
        this.setData({entityPatam: data})
        resolve(data);
      })
    })
  },
  //刷新列表
  refreshList(){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面
    beforePage.refreshData();
  },

  //获取模块布局
  getLayoutJson(tableid,fn){
    let url = 'Custom/get_html_WXMiniProgram',
      post = {'table_id': tableid};
    return new Promise((resolve => {
      wx.$post(1,url,post).then((res)=>{
        if (res.errcode != 0)return;
        let data = res.data.row && res.data.row[0];
        if (!data){
          let url2 = 'Custom/get_html'
          wx.$post(1,url2,post).then(res=>{
            if (res.errcode != 0)return;
            let data = res.data.row && res.data.row[0];
            resolve(data);
          });
          return
        }

        resolve(data);
      })
    }))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();

    let entity = options.entity,
      rowid = options.rid,
      status = options.status,
      obj = {
        tableid: entity,
        rowid: rowid,
        aprRowid: rowid,
        status:status,
        isDisplay: status === 'edit',
      };
    if (status === 'edit') {
      await this.getEntityParam(entity);
      if (this.data.entityPatam.is_verify) {  //当前编辑界面、已启用审批
        obj.approveFlag = true;
      }
    }

    this.setData(obj);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
